package video.application.service;

import video.domain.model.Video;
import video.domain.repository.VideoRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class VideoService {

    private final VideoRepository repo;

    @Autowired
    public VideoService(VideoRepository repo) {
        this.repo = repo;
    }

    public Video create(Video video) {
        return repo.save(video);
    }

    public void delete(Long id) {
        repo.deleteById(id);
    }

    public Optional<Video> get(Long id) {
        return repo.findById(id);
    }

    public List<Video> listAll() {
        return repo.findAll();
    }

    public List<Video> listVisible() {
        return repo.findByIsDeletedFalseOrderByCreateTimeDesc();
    }

    public Video update(Long id, Video newVideo) {
        return repo.findById(id).map(video -> {
            if (newVideo.getVideoTitle() != null) {
                video.setVideoTitle(newVideo.getVideoTitle());
            }
            if (newVideo.getVideoContent() != null) {
                video.setVideoContent(newVideo.getVideoContent());
            }
            if (newVideo.getVideoLink() != null) {
                video.setVideoLink(newVideo.getVideoLink());
            }
            return repo.save(video);
        }).orElseThrow(() -> new RuntimeException("Video not found"));
    }
}
